<template>
  <div class="comment-form" :class="{ 'is-compact': compact }">
    <div v-if="!compact" class="form-header">
      <h3>{{ parentId ? '发表回复' : '发表评论' }}</h3>
      <p v-if="replyToNickname" class="subtitle">回复 @{{ replyToNickname }}</p>
    </div>

    <el-form ref="formRef" :model="form" :rules="formRules" class="comment-form-content">
      <el-form-item prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="compact ? 3 : 4"
          :placeholder="placeholder || (parentId ? '写下你的回复...' : '写下你的评论...')"
          class="comment-textarea"
        />
      </el-form-item>

      <!-- 用户信息输入区域 -->
      <div class="user-info" :class="{ 'is-compact': compact }">
        <el-form-item prop="nickname" class="user-input">
          <el-input
            v-model="form.nickname"
            placeholder="昵称"
            prefix-icon="User"
            :size="compact ? 'small' : 'default'"
          />
        </el-form-item>

        <el-form-item prop="email" class="user-input">
          <el-input
            v-model="form.email"
            placeholder="邮箱"
            prefix-icon="Message"
            :size="compact ? 'small' : 'default'"
          />
        </el-form-item>

        <el-form-item prop="website" class="user-input">
          <el-input
            v-model="form.website"
            placeholder="网站（可选）"
            prefix-icon="Link"
            :size="compact ? 'small' : 'default'"
          />
        </el-form-item>
      </div>

      <div class="form-actions">
        <div class="action-left">
          <el-button
            v-if="commentStore.isUserInfoComplete()"
            text
            type="info"
            :size="compact ? 'small' : 'default'"
            @click="clearUserInfo"
          >
            清除用户信息
          </el-button>
        </div>
        <div class="action-right">
          <el-button v-if="parentId" size="small" @click="handleCancel">取消</el-button>
          <el-button
            type="primary"
            :loading="submitting"
            :size="compact ? 'small' : 'default'"
            @click="handleSubmit"
          >
            {{ parentId ? '回复' : '发表评论' }}
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { commentSave } from '@/api/comment'
  import { useCommentStore } from '@/stores/comment'
  import type { CommentSaveParam } from '@/types/comment'

  const props = defineProps<{
    blogId: string
    parentId?: string
    replyToUserId?: string
    replyToNickname?: string
    placeholder?: string
    compact?: boolean
  }>()

  const emit = defineEmits<{
    commentSubmitted: []
    cancel: []
  }>()

  const commentStore = useCommentStore()
  const formRef = ref()
  const submitting = ref(false)

  const form = reactive({
    content: '',
    nickname: commentStore.nickname || '',
    email: commentStore.email || '',
    website: commentStore.website || '',
  })

  const formRules = {
    content: [
      { required: true, message: '内容不能为空', trigger: 'blur' },
      { min: 1, max: 1000, message: '内容长度在1-1000字符之间', trigger: 'blur' },
    ],
    nickname: [
      { required: true, message: '昵称不能为空', trigger: 'blur' },
      { min: 1, max: 50, message: '昵称长度在1-50字符之间', trigger: 'blur' },
    ],
    email: [
      { required: true, message: '邮箱不能为空', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    ],
    website: [{ type: 'url', message: '请输入正确的网站地址', trigger: 'blur' }],
  }

  const handleSubmit = async () => {
    if (submitting.value) return

    try {
      await formRef.value.validate()
    } catch {
      return
    }

    submitting.value = true
    try {
      const param: CommentSaveParam = {
        blogId: props.blogId,
        parentId: props.parentId,
        replyToUserId: props.replyToUserId,
        replyToNickname: props.replyToNickname,
        content: form.content,
        nickname: form.nickname,
        email: form.email,
        website: form.website || undefined,
      }

      await commentSave(param)

      // 保存用户信息到store（会自动持久化到localStorage）
      commentStore.setUserInfo({
        nickname: form.nickname,
        email: form.email,
        website: form.website,
      })

      ElMessage.success(props.parentId ? '回复发表成功！' : '评论发表成功！')

      // 只重置评论内容，保留用户信息
      form.content = ''

      emit('commentSubmitted')
    } catch (error) {
      console.error('提交评论失败:', error)
      ElMessage.error('发表失败，请稍后重试')
    } finally {
      submitting.value = false
    }
  }

  const handleCancel = () => {
    form.content = ''
    emit('cancel')
  }

  const clearUserInfo = () => {
    commentStore.clearUserInfo()
    ElMessage.success('用户信息已清除')
  }

  // 监听store中的用户信息变化，同步到表单
  watch(
    () => [commentStore.nickname, commentStore.email, commentStore.website],
    ([nickname, email, website]) => {
      form.nickname = nickname
      form.email = email
      form.website = website
    },
    { immediate: true }
  )
</script>

<style scoped>
  .comment-form {
    background: var(--bg-color, #ffffff);
    border-radius: 12px;
    padding: 0;
    box-shadow: none;
    border: none;
  }

  .comment-form.is-compact {
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border: 1px solid var(--border-color, #e4e7ed);
    border-radius: 10px;
  }

  .form-header {
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border-color, #e4e7ed);
  }

  .form-header h3 {
    font-size: 20px;
    color: var(--text-primary, #333);
    margin: 0 0 8px 0;
    font-weight: 600;
  }

  .subtitle {
    color: var(--text-secondary, #666);
    font-size: 14px;
    margin: 0;
    background: linear-gradient(135deg, rgba(64, 158, 255, 0.1), rgba(64, 158, 255, 0.05));
    padding: 6px 12px;
    border-radius: 16px;
    display: inline-block;
    font-weight: 500;
  }

  .comment-form-content {
    width: 100%;
  }

  .comment-textarea :deep(.el-textarea__inner) {
    border-radius: 10px;
    padding: 16px;
    font-size: 15px;
    line-height: 1.6;
    resize: vertical;
    min-height: 100px;
    border: 2px solid var(--border-color, #e4e7ed);
    transition: all 0.3s ease;
    background: var(--bg-color, #ffffff);
    color: var(--text-primary, #333);
  }

  .comment-textarea :deep(.el-textarea__inner):focus {
    border-color: var(--primary-color, #409eff);
    box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.1);
  }

  .comment-textarea :deep(.el-textarea__inner):hover {
    border-color: var(--primary-color, #409eff);
  }

  .user-info {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
  }

  .user-info.is-compact {
    gap: 12px;
    margin-bottom: 16px;
  }

  .user-input {
    flex: 1;
  }

  .user-input :deep(.el-input__wrapper) {
    border-radius: 8px;
    padding: 0;
    border: 2px solid var(--border-color, #e4e7ed);
    box-shadow: none;
    transition: all 0.3s ease;
    background: var(--bg-color, #ffffff);
  }

  .user-input :deep(.el-input__wrapper):hover {
    border-color: var(--primary-color, #409eff);
  }

  .user-input :deep(.el-input__wrapper.is-focus) {
    border-color: var(--primary-color, #409eff);
    box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.1);
  }

  .user-input :deep(.el-input__inner) {
    padding: 10px;
    font-size: 14px;
    color: var(--text-primary, #333);
    background: transparent;
  }

  .user-input :deep(.el-input__prefix) {
    left: 16px;
    color: var(--text-secondary, #909399);
  }

  .user-input :deep(.el-input__prefix .el-icon) {
    font-size: 16px;
  }

  .user-input :deep(.el-icon.el-input__icon) {
    margin-left: 10px;
  }

  .form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
    border-top: 1px solid var(--border-color, #f0f2f5);
  }

  .action-left {
    flex: 1;
  }

  .action-left .el-button {
    color: var(--text-secondary, #909399);
    background: transparent;
    border: none;
    padding: 8px 0;
    font-size: 13px;
    transition: all 0.3s ease;
  }

  .action-left .el-button:hover {
    color: var(--danger-color, #f56c6c);
    background: rgba(245, 108, 108, 0.1);
    border-radius: 6px;
    padding: 8px 12px;
  }

  .action-right {
    display: flex;
    gap: 12px;
  }

  .action-right .el-button {
    border-radius: 20px;
    padding: 10px 24px;
    font-weight: 500;
    transition: all 0.3s ease;
    border: 2px solid transparent;
  }

  .action-right .el-button:not(.el-button--primary) {
    background: var(--bg-secondary, #f8f9fa);
    border-color: var(--border-color, #e4e7ed);
    color: var(--text-secondary, #666);
  }

  .action-right .el-button:not(.el-button--primary):hover {
    background: var(--text-secondary, #909399);
    border-color: var(--text-secondary, #909399);
    color: white;
    transform: translateY(-1px);
  }

  .action-right .el-button--primary {
    /* 使用主题变量 --primary-gradient 作为主按钮渐变背景色，自动适配浅色/深色模式 */
    background: var(--primary-gradient);
    border-color: var(--primary-color, #3b82f6);
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
  }

  .action-right .el-button--primary:hover {
    /* hover 态同样使用主题渐变色，保持风格一致 */
    background: var(--primary-gradient);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  }

  .action-right .el-button--primary.is-loading {
    background: var(--primary-color, #409eff);
    transform: none;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .user-info {
      flex-direction: column;
      gap: 12px;
    }

    .user-info.is-compact {
      gap: 10px;
    }

    .form-actions {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;
    }

    .action-left {
      order: 2;
      text-align: center;
    }

    .action-right {
      order: 1;
      justify-content: center;
    }
  }
</style>
